package com.module.ble.repo

import com.module.ble.db.HealthExaManager
import com.module.ble.db.HeartEntryTimeQueryHelper
import com.module.ble.db.table.UserHeartEntryTime
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/3/28
 * <p>
 * 描述：仓库类，所有相关的数据操作都在此类中进行，数据库的增、删、改、查操作
 * <p>
 * 修订历史：
 */
class HeartEntryTimeRepo private constructor() {

    private val refreshTrigger = MutableStateFlow(0)

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HeartEntryTimeRepo() }
    }

    private val dao = HealthExaManager.mHeartEntryTimeDao

    private val scope = CoroutineScope(Dispatchers.IO)

    /**
     * 查找该时间数据
     */
    fun findByTime(time :String): UserHeartEntryTime? {
        //数据库查找所有数据
        return dao?.findByTime(time)
    }

    /**
     * 查找所有数据
     */
    fun findAll(): List<UserHeartEntryTime>? {
        //数据库查找所有数据
        return dao?.findAll()
    }

    /**
     * 查找所有数据
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    fun findAllFlow(): Flow<List<UserHeartEntryTime>> = refreshTrigger.flatMapLatest { dao?.findAllFlow() ?: flowOf(emptyList())}

    /**
     * 查找所有数据
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    fun findByFieldValueFlow(fieldName: String): Flow<List<UserHeartEntryTime>> = refreshTrigger.flatMapLatest { dao?.findByFieldValueFlow(HeartEntryTimeQueryHelper.createFieldEqualsOneQuery(fieldName)) ?: flowOf(emptyList())}

    /**
     * 查找所有数据
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    fun findByFieldEqualsOneQueryFlowRo(fieldNames: Array<String>): Flow<List<UserHeartEntryTime>> = refreshTrigger.flatMapLatest { dao?.findByFieldValueFlow(
        HeartEntryTimeQueryHelper.createFieldEqualsOneQuery(fieldNames)) ?: flowOf(emptyList())}

    /**
     * 插入数据
     */
    fun add2DB(data: UserHeartEntryTime?) {
        data?.let { dataIt->
            scope.launch {
                dao?.insertOrUpdate(dataIt)
            }
        }
    }

    /**
     * 删除数据库中数据
     */
    private fun del2DB(data: UserHeartEntryTime?) {
        data?.let { dataIt->
            scope.launch {
                dao?.delete(dataIt)
            }
        }
    }

    /**
     * 自动触发 Flow 的更新，进而更新 LiveData
     */
    fun refreshData() {
        refreshTrigger.value += 1
    }
}